
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.Socket;
import java.net.SocketException;

public class ChatClient extends Frame {

    TextArea ta = new TextArea();
    TextField tf = new TextField();
    Socket s = null;
    DataOutputStream dos = null;
    DataInputStream dis = null;
    boolean bConnected = false;

    public static void main(String[] args) {
        new ChatClient().launch();
    }

    public void launch() {
        setBounds(300, 330, 600, 500);
        setLayout(new BorderLayout());
        add(ta, BorderLayout.NORTH);
        add(tf, BorderLayout.SOUTH);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                disconnect();
                System.exit(0);
            }
        });
        tf.addActionListener(new TFMyListener());
        pack();
        setVisible(true);
        connect();
        new Thread(new TFReceveive()).start();
    }

    public void connect() {
        try {
            s = new Socket("127.0.0.1", 8888);
            dos = new DataOutputStream(s.getOutputStream());
            dis = new DataInputStream(s.getInputStream());
            System.out.println("connected");
            bConnected = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void disconnect() {
        try {
            dos.close();
            dis.close();
            s.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }


    private class TFMyListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String str = tf.getText().trim();
//            ta.setText(str);
            tf.setText("");
            try {
                dos.writeUTF(str);
                dos.flush();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

    }

    class TFReceveive implements Runnable {
        @Override
        public void run() {
            try {
                while (bConnected) {
                    String str = dis.readUTF();
                    System.out.println(str);
                    ta.setText(ta.getText() + str + '\n');
                }
            } catch (SocketException e) {
                System.out.println("对方退出了！");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
